﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TBlog.Web.Common.PageHelper;
using TBlog.Web.Models;
using TBlog.Web.Service;
using TBlog.Web.ViewModel;

namespace TBlog.Web.Controllers
{
    public class CategoryController : BaseController
    {
        //
        // GET: /Category/
        ICategoryService _categoryserice;
        public CategoryController(ICategoryService categoryservice)
        {
            _categoryserice = categoryservice;
        }
        [HttpGet]
        public ActionResult Create()
        {

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(Category model)
        {
            model.CreateTime = DateTime.Now;
            if (_categoryserice.Add(model) > 0)
                return RedirectToAction("GetCategory", "Category");
            return Json(_categoryserice.GetJsonMessage(true, "", "添加分类信息失败"));






        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(true)]
        public ActionResult Edit(Category model)
        {
            var id = Request["id"];
            var entity = _categoryserice.GetByID(Convert.ToInt32(id));
            entity.CategoryName = model.CategoryName;

            _categoryserice.Update(entity);
            return RedirectToAction("GetCategory", "Category");
        }
        [HttpGet]
        public ActionResult Edit()
        {
            var id = Request["id"];
            var model = _categoryserice.GetByID(Convert.ToInt32(id));

            return View(model);
        }
        [HttpGet]
        public ActionResult GetCategory()
        {
            var model = _categoryserice.GetCategory(a => a.ID == a.ID, new PageListRequest(1, 10, true));
            return View("CategoryList", model);
        }

        public JsonResult CheckName(string name)
        {
            var res = _categoryserice.IsExists(name);
            return Json(_categoryserice.GetJsonMessage(true, "", res ? "分类名称已经存在，请更换或直接使用" : ""));

        }
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var res = _categoryserice.Delete(id);
            return Json(_categoryserice.GetJsonMessage(true, "", res > 0 ? "删除成功" : "删除失败"));
        }
    }
}
